import React, { useRef } from "react";

export default function Menu(props) {
  const menuRef = useRef();
  const { parentId, name, children, unFoldRef, setUnFoldRef } = props;

  const unFold = (ref)=>{
    return ()=>{
      if(unFoldRef===null){
        setUnFoldRef(ref)
        ref.current.style.display = "block"
      }else if(ref!==unFoldRef){
        ref.current.style.display = "block"
        unFoldRef.current.style.display = "none"
        setUnFoldRef(ref)
      }else{
        setUnFoldRef(null)
        ref.current.style.display = "none"
      }
    }
  }

  const menu = () => {
    let ele = null
    if (children) {
      if (parentId !== 0) {
        ele = (<li><a href="#" onClick={unFold(menuRef)}>{name}</a><ul ref={menuRef}>{children}</ul> </li>)
      } else {
        ele = <>{children}</>
      }
    } else {
        ele = <li><a href="#">{name}</a></li>
    }
    return ele
  };

  return menu();
}
